class Admin::InnoawardsController < Admin::AdminController
  before_action :find_innoaward, except: [:index, :new, :create]
  before_action :gon_data, only: [:new, :edit, :partners]

  def index
    @innoawards = Innoaward.order(created_at: :desc).all.page params[:page]
  end

  def new
    @innoaward = Innoaward.new
    @product = Product.first
  end

  def create
    @innoaward = Innoaward.new(inno_params)
    if @innoaward && @innoaward.save
      redirect_to admin_innoaward_path(@innoaward)
    else
      render :new
    end
  end

  def upload_image

  end

  def show
  end

  def edit
  end

  def update
    if @innoaward.update(inno_params)
      redirect_to admin_innoaward_path(@innoaward)
    else
      render :edit
    end
  end

  def update_partners
    @innoaward.partners['categories'] = params['categories']
    @innoaward.partners['detail'] = JSON.parse(params['detail'])
    respond_to do |format|
      if @innoaward.save
        format.json { render json: @innoaward.partners, status: :created, location: [:admin, @innoaward] }
      else
        format.json { render json: @innoaward.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @innoaward.destroy
    redirect_to admin_innoawards_path
  end

  def ranks
    @award = Award.find(params[:award_id])
    @ranks = @innoaward.ranks.where(award_id: params[:award_id]).order('ranks.order').page params[:page]
  end

  def partners
    @partners = @innoaward.partners
    gon.listPartners = @partners
  end

  private
  def find_innoaward
    @innoaward = Innoaward.find(params[:id])
  end

  def gon_data
    gon.innoaward = @innoaward
    gon.partners = Partner.all.map{|partner| {id: partner['id'], name: partner['name']}}
  end

  def inno_params
    schedule = params.require(:innoaward).require(:schedule).permit!
    others = params.require(:innoaward).permit(:year, :title, :about, :rule, :schedule, {partners: [:category, :index, :partners]}, {header_images: []}, {header_descs: []}, :extra_info)
    others['schedule'] = schedule
    others
  end
end
